package com.gcloud.controller.network.handler.api.floatingip.standard;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.gcloud.controller.network.service.IFloatingIpService;
import com.gcloud.controller.utils.ApiUtil;
import com.gcloud.core.exception.GCloudException;
import com.gcloud.core.handle.ApiHandler;
import com.gcloud.core.handle.MessageHandler;
import com.gcloud.core.util.BeanUtil;
import com.gcloud.framework.db.PageResult;
import com.gcloud.header.ApiVersion;
import com.gcloud.header.Module;
import com.gcloud.header.SubModule;
import com.gcloud.header.network.model.EipAddressSetType;
import com.gcloud.header.network.model.standard.StandardEipAddressSetType;
import com.gcloud.header.network.msg.api.DescribeEipAddressesMsg;
import com.gcloud.header.network.msg.api.standard.StandardApiDescribeEipAddressesMsg;
import com.gcloud.header.network.msg.api.standard.StandardApiDescribeEipAddressesReplyMsg;

@ApiHandler(module=Module.ECS,subModule=SubModule.EIPADDRSS,action="DescribeEipAddresses", versions = {ApiVersion.Standard})
public class StandardApiDescribeEipAddressesHandler extends MessageHandler<StandardApiDescribeEipAddressesMsg, StandardApiDescribeEipAddressesReplyMsg>{

	@Autowired
	IFloatingIpService eipService;
	
	@Override
	public StandardApiDescribeEipAddressesReplyMsg handle(StandardApiDescribeEipAddressesMsg msg)
			throws GCloudException {
		PageResult<EipAddressSetType> response = eipService.describeEipAddresses(toParams(msg));
		PageResult<StandardEipAddressSetType> stdResponse = ApiUtil.toPage(response, toStandardReply(response.getList()));
		
		StandardApiDescribeEipAddressesReplyMsg replyMsg = new StandardApiDescribeEipAddressesReplyMsg();
        replyMsg.init(stdResponse);
        return replyMsg;
	}
	
	private DescribeEipAddressesMsg toParams(StandardApiDescribeEipAddressesMsg msg) {
		DescribeEipAddressesMsg params = BeanUtil.copyProperties(msg, DescribeEipAddressesMsg.class);
		return params;
	}
	
	private List<StandardEipAddressSetType> toStandardReply(List<EipAddressSetType> list) {
		if(null == list) {
			return null;
		}
		
		List<StandardEipAddressSetType> stdList = new ArrayList<>();
		for (EipAddressSetType item : list) {
			StandardEipAddressSetType tmp = BeanUtil.copyProperties(item, StandardEipAddressSetType.class);
			stdList.add(tmp);
		}
		return stdList;
	}

}
